<!--  SubForm 子表单展示模块 -->
<template>
  <div class="positionCont">
    <t-input
      v-model="mapAdd"
      style="width: 300px; margin-right: 20px"
      placeholder="请选择"
      @change="mapPointionSearch"
    />
    <div v-if="data.data.getlatAndLg">
      <span>经纬度：</span>
      <span>{{ posLnglat }}</span>
    </div>
  </div>
  <div
    v-if="data.type === 'position'"
    :id="`map${data.id}`"
    ref="mapNode"
    style="height: 10vh; width: 100%; min-height: 300px"
  ></div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const props = defineProps({
  data: Object
})
const emit: Function = defineEmits(['valueChange'])

onMounted(() => {
  initMap()
})

const map = ref()
const mapAdd = ref('请选择')
const posLnglat = ref(['请选择'])
const addressSearch = ref()
const mapNode = ref()
const initMap = () => {
  AMapLoader.load({
    key: '8a1b9d2eb62671c0b1b5f06e5effd81b', // 申请好的Web端开发者Key，首次调用 load 时必填
    plugins: [
      'AMap.ToolBar', // 工具条
      'AMap.Scale', // 比例尺
      'AMap.Geolocation', // 定位
      'AMap.PlaceSearch',
      'AMap.Geocoder'
    ] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      map.value = new AMap.Map(`map${props.data.id}`, {
        resizeEnable: true,
        rotateEnable: true,
        pitchEnable: true,
        zoom: 11,
        pitch: 80,
        expandZoomRange: true,
        zooms: [3, 20],
        center: [116.397428, 39.90923] // 初始化地图中心点位置
      })
      addressSearch.value = new AMap.PlaceSearch({
        map: mapNode.value,
        autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        extensions: 'base' // 返回基本地址信息
      })
      map.value.on('click', async (e) => {
        const lng = e.lnglat.lng
        const lat = e.lnglat.lat
        const lnglat = [lng, lat]
        posLnglat.value = lnglat
        const geocoder = new AMap.Geocoder()
        await geocoder.getAddress(lnglat, (status, data) => {
          if (status === 'complete') {
            mapAdd.value = data.regeocode.formattedAddress
          } else {
            mapAdd.value = '地址获取失败'
          }
        })
        const data = props.data.data.getlatAndLg
          ? { address: mapAdd.value, Lnglat: [lng, lat] }
          : mapAdd.value
        setTimeout(() => {
          emit('valueChange', { item: props.data, data })
        }, 100)
      })
    })
    .catch((e) => {
      console.log(e)
    })
}
const mapPointionSearch = (data) => {
  emit('valueChange', { item: props.data, data })
}
</script>
<style lang="less" scoped>
.positionCont {
  padding: 5px 10px 20px 0;
  display: flex;
  line-height: 32px;
}
</style>
